// pages/editPassword/editPassword.js
const API = require('../../utils/api.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    usertype: "",
    rawPassword: "",
    newPassword: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(app.globalData.isLogin){
      this.setData({
        usertype: app.globalData.usertype
      })
    }
  },

  inputRawPassword: function (e) {
    this.setData({
      rawPassword: e.detail.value
    })
  },

  inputNewPassword: function (e) {
    this.setData({
      newPassword: e.detail.value
    })
  },

  updatePassword: function () {
    let that = this
    if(that.data.rawPassword == ""){
      wx.showToast({
        title: '请输入旧密码',
        icon: 'none'
      })
      return
    }else if(that.data.newPassword == ""){
      wx.showToast({
        title: '请输入新密码',
        icon: 'none'
      })
      return
    }else if(that.data.rawPassword == that.data.newPassword){
      wx.showToast({
        title: '旧密码与新密码一致！',
        icon: 'none'
      })
      return
    }else{
      wx.showLoading({
        title: '修改中',
      })
      wx.request({
        url: that.getUpdateApi(that.data.usertype),
        method: 'POST',
        data: {
          "id": app.globalData.userinfo.id,
          "rawPassword": that.data.rawPassword,
          "encryptedPassword": app.globalData.userinfo.password,
          "newPassword": that.data.newPassword
        },
        success (res) {
          wx.hideLoading()
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
          if(res.data.code == "SUCCESS"){
            app.globalData.userinfo = res.data.data
            wx.setStorageSync('userinfo', res.data.data)
          }
        },
        fail(res) {
          wx.hideLoading()
        }
      })
    }
  },

  getUpdateApi: function (type) {
    if (type == "customer") {
      return API.Customer.updatePassword
    } else if (type == "seller") {
      return API.Seller.updatePassword
    } else if (type == "producer") {
      return API.Producer.updatePassword
    } else if (type == "transporter") {
      return API.Transporter.updatePassword
    }
  }

})